import wx
import copy
from DataTool import DataTool

class DiaTable4Add(wx.Dialog):
    Names = ['名称', '规格', '单位', '价格（除税）']
    Widths = [(120, -1), (300, -1), (50, -1), (60, -1), (60, -1),]
    Choices2 = ['光缆', '电缆', '塑料', '水泥', '其他']
    Choices1 = ['设备', '设备(不安装)']
    ListCtrlNames = ['名称', '规格', '单位', '价格（除税）', '材料类型']
    ListCtrlWidths = [120, 300, 50, 100, 100]
    BtnNames = ['拷贝', '上移', '下移', '修改...', '删除', '保存', '取消']
    Fun = ['self.OnCopy', 'self.OnUp', 'self.OnDown', 'self.OnChange',
          'self.OnDelete', 'self.OnSave', 'self.OnCancel', 'self.OnUp', 
          'self.OnUp']
    def __init__(self, parent, title, *args, **kwargs):
        self.gridname = kwargs.get('name', '表四设备')
        self.datas = []
        self.tempaddindexs = [0]
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.inputsizer = wx.BoxSizer(wx.HORIZONTAL)
        # 初始化第一排
        self.InitTextCtrl()
        # 初始化listctrl
        listctrl = wx.ListCtrl(self, -1, style=wx.LC_REPORT, size=(-1, 300), name='添加材料')
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectedA, listctrl)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnDisSelectedA, listctrl)
        self.InitListCtrl()
        # 初始化btn
        self.InitBtn(btnsizer)

        mainsizer.Add(self.inputsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        mainsizer.Add(listctrl, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=15)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.ALIGN_RIGHT, border=5)

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)

    def OnAdd(self, event):
        temp = []
        waringemptnames = ['名称', '单位', '价格（除税）']
        waringnumnames = ['价格（除税）']
        waringemptmessage = '数据不能为空！'
        waringnummessage = '填入数据必须为数字！'

        for name in self.Names:
            obj = self.FindWindowByName(name+'textctrl')
            text = obj.GetLineText(0)
            if name in waringemptnames and text == '':
                wx.MessageDialog(self, '"' + name + '"' + waringemptmessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                return
            if name in waringnumnames and not self.isnum(text):
                wx.MessageDialog(self, '"' + name + '"' + waringnummessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING).ShowModal()
                return
            temp.append(text)
        choice = self.FindWindowByName('choicer')
        choicetext = choice.GetString(choice.GetSelection())
        temp.append(choicetext)
        self.datas.append(temp)
        self.Refresh()
        
        handler = self.FindWindowByName('清除')
        thisid = handler.GetId()
        evt = wx.CommandEvent(wx.EVT_BUTTON.typeId, thisid)
        wx.PostEvent(handler, evt)
    
    def OnDisSelectedA(self, event):
        Oindex = event.GetIndex()
        Tindex = self.tempaddindexs.index(Oindex)
        self.tempaddindexs.remove(Oindex)
        self.tempaddlist.pop(Tindex)

    def OnSelectedA(self, event):
        
        listctrl = event.GetEventObject()
        scount = listctrl.GetSelectedItemCount()
        firsts =listctrl.GetFirstSelected()
        colcount = len(self.datas[0])
        
        relist = []
        temp = []
        serials = []
        indexs = []
        for col in range(colcount):
            temp.append(listctrl.GetItemText(firsts, col))
        relist.append(temp)
        serial = listctrl.GetItemText(firsts)
        serials.append(serial)
        indexs.append(firsts)

        if scount > 1:
            nexts = firsts
            for i in range(scount-1):
                temp = []
                nexts = listctrl.GetNextSelected(nexts)
                for col in range(colcount):
                    temp.append(listctrl.GetItemText(nexts, col))
                relist.append(temp)
                serial = listctrl.GetItemText(nexts)
                serials.append(serial)
                indexs.append(nexts)
        
        self.tempaddlist = relist
        self.tempaddindexs = indexs

    def OnClear(self, event):
        for name in self.Names:
            obj = self.FindWindowByName(name+'textctrl')
            obj.Clear()

    def OnCopy(self, event):
        listctrl = self.FindWindowByName('添加材料')
        tempaddlist = copy.copy(self.tempaddlist)
        tempaddindexs = copy.copy(self.tempaddindexs)
        tempaddlist.reverse()
        tempaddindexs.reverse()
        for index, row in enumerate(tempaddindexs):
            self.datas.insert(row, tempaddlist[index])
        self.Refresh()
        sizeh = 20
        listctrl.ScrollList(0, self.tempaddindexs[-1]*sizeh)

    def OnUp(self, event):
        relist = copy.copy(self.tempaddlist)
        indexs = copy.copy(self.tempaddindexs)
        for index, row in enumerate(indexs):
            if row == 0:
                continue
            else:
                self.datas.insert(row - 1, relist[index])
                self.datas.pop(row + 1)
                self.tempaddindexs[index] = row - 1
        self.Refresh()
    
    def OnDown(self, event):
        relist = copy.copy(self.tempaddlist)
        indexs = copy.copy(self.tempaddindexs)
        relist.reverse()
        indexs.reverse()
        for index, row in enumerate(indexs):
            if row == len(self.datas) - 1:
                continue
            else:
                self.datas.insert(row + 2, relist[index])
                self.datas.pop(row)
                self.tempaddindexs[index] = row + 1
        self.Refresh()

    def OnDelete(self, event):
        indexs = copy.copy(self.tempaddindexs)
        indexs.reverse()
        for row in indexs:
            self.datas.pop(row)
        self.Refresh()

    def OnChange(self, event):
        index = self.tempaddindexs[0]
        dialog = DiaTable4Change(self, '修改单项', data=self.datas[index])
        data = dialog.ShowModal()
        if data == 5101:
            return
        else:
            self.datas[index] = data
            self.Refresh()
        dialog.Destroy()
            
    def OnSave(self, event):
        self.EndModal(retCode=1)
    
    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.datas
        else:
            return 5101

    def InitTextCtrl(self):
        for index, name in enumerate(self.Names):
            thissizer = wx.BoxSizer(wx.VERTICAL)
            statictext = wx.StaticText(self, -1, label=name, name=name+'statictext')
            textctrl = wx.TextCtrl(self, -1, size=self.Widths[index], name=name+'textctrl')
            thissizer.Add(statictext, 0, flag=wx.ALL|wx.EXPAND, border=5)
            thissizer.Add(textctrl, 0, flag=wx.ALL|wx.EXPAND, border=5)
            self.inputsizer.Add(thissizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        thissizer = wx.BoxSizer(wx.VERTICAL)
        # 
        if self.gridname == '表四设备':
            choices = self.Choices1 
        else:
            choices = self.Choices2
        # 
        choicer = wx.Choice(self, -1, choices=choices, name='choicer')
        name = '材料类型'
        statictext = wx.StaticText(self, -1, label=name, name=name+'statictext')
        thissizer.Add(statictext, 0, flag=wx.ALL|wx.EXPAND, border=5)
        thissizer.Add(choicer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        self.inputsizer.Add(thissizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        choicer.SetSelection(0)

        thissizer = wx.BoxSizer(wx.VERTICAL)
        btnclear = wx.Button(self, -1, label='清除', name='清除')
        btnadd = wx.Button(self, -1, label='添加', name='添加')
        self.Bind(wx.EVT_BUTTON, self.OnAdd, btnadd)
        self.Bind(wx.EVT_BUTTON, self.OnClear, btnclear)

        thissizer.Add(btnclear, 0, flag=wx.ALL|wx.EXPAND, border=3)
        thissizer.Add(btnadd, 0, flag=wx.ALL|wx.EXPAND, border=2)

        self.inputsizer.Add(thissizer, 0, flag=wx.ALL|wx.EXPAND, border=5)

    def InitListCtrl(self):
        listctrl = self.FindWindowByName('添加材料')
        for index, name in enumerate(self.ListCtrlNames):
            listctrl.InsertColumn(index, name)
            listctrl.SetColumnWidth(index, self.ListCtrlWidths[index])

    def InitBtn(self, sizer):
        for index, name in enumerate(self.BtnNames):
            btn = wx.Button(self, -1, label=name, name=name+'btn')
            self.Bind(wx.EVT_BUTTON, eval(self.Fun[index]), btn)
            # self.Bind(wx.EVT_BUTTON, self.OnCopy, btn)
            sizer.Add(btn, 0, flag=wx.ALL|wx.EXPAND, border=5)

    def Refresh(self):
        listctrl = self.FindWindowByName('添加材料')
        listctrl.DeleteAllItems()
        for row, rowv in enumerate(self.datas):
            index = listctrl.InsertItem(row, rowv[0])
            for col, value in enumerate(rowv[1:]):
                listctrl.SetItem(index, col+1, value)
        for i in self.tempaddindexs:
            listctrl.Select(i)
    
    def isnum(self, string):
        try:
            if string=='NaN':
                return False
            float(string)
            return True
        except ValueError:
            return False

class DiaTable4Change(wx.Dialog):
    Names = ['名称', '规格', '单位', '价格（除税）']
    Widths = [(120, -1), (300, -1), (50, -1), (60, -1), (60, -1),]
    Choices2 = ['光缆', '电缆', '塑料', '水泥', '其他']
    Choices1 = ['设备', '设备(不安装)']
    ListCtrlNames = ['名称', '规格', '单位', '价格（除税）', '材料类型']
    BtnNames = ['保存', '取消']
    Fun = ['self.OnSave', 'self.OnCancel', ]
    def __init__(self, parent, title, *args, **kwargs):
        self.gridname = kwargs.get('name', '表四设备')
        self.data = kwargs.get('data', ['', '', '', '', ''])
        self.tempaddindexs = [0]
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.inputsizer = wx.BoxSizer(wx.HORIZONTAL)
        # 初始化第一排
        self.InitTextCtrl()
        # 初始化btn
        self.InitBtn(btnsizer)

        mainsizer.Add(self.inputsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.ALIGN_RIGHT, border=5)

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)
    
    def InitTextCtrl(self):
        for index, name in enumerate(self.Names):
            thissizer = wx.BoxSizer(wx.VERTICAL)
            statictext = wx.StaticText(self, -1, label=name, name=name+'changestatictext')
            textctrl = wx.TextCtrl(self, -1, size=self.Widths[index], name=name+'changetextctrl', value=str(self.data[index]))
            thissizer.Add(statictext, 0, flag=wx.ALL|wx.EXPAND, border=5)
            thissizer.Add(textctrl, 0, flag=wx.ALL|wx.EXPAND, border=5)
            self.inputsizer.Add(thissizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        thissizer = wx.BoxSizer(wx.VERTICAL)
        # 
        if self.gridname == '表四设备':
            choices = self.Choices1 
        else:
            choices = self.Choices2
        # 
        choicer = wx.Choice(self, -1, choices=choices, name='changechoicer')
        name = '材料类型'
        statictext = wx.StaticText(self, -1, label=name, name=name+'changestatictext')
        thissizer.Add(statictext, 0, flag=wx.ALL|wx.EXPAND, border=5)
        thissizer.Add(choicer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        self.inputsizer.Add(thissizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        stringindex = choicer.FindString(self.data[4])
        if stringindex == wx.NOT_FOUND:
            choicer.SetSelection(0)
        else:
            choicer.SetSelection(stringindex)

    def InitBtn(self, sizer):
        for index, name in enumerate(self.BtnNames):
            btn = wx.Button(self, -1, label=name, name=name+'btn')
            self.Bind(wx.EVT_BUTTON, eval(self.Fun[index]), btn)
            # self.Bind(wx.EVT_BUTTON, self.OnCopy, btn)
            sizer.Add(btn, 0, flag=wx.ALL|wx.EXPAND, border=5)

    def OnSave(self, event):
        waringemptnames = ['名称', '单位', '价格（除税）']
        waringnumnames = ['价格（除税）']
        waringemptmessage = '数据不能为空！'
        waringnummessage = '填入数据必须为数字！'

        for index, name in enumerate(self.Names):
            obj = self.FindWindowByName(name+'changetextctrl')
            text = obj.GetLineText(0)
            if name in waringemptnames and text == '':
                dia = wx.MessageDialog(self, '"' + name + '"' + waringemptmessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
                dia.ShowModal()
                dia.Destroy()
                return
            if name in waringnumnames and not self.isnum(text):
                dia = wx.MessageDialog(self, '"' + name + '"' + waringnummessage,
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
                dia.ShowModal()
                dia.Destroy()
                return
            self.data[index] = text
        choice = self.FindWindowByName('changechoicer')
        choicetext = choice.GetString(choice.GetSelection())
        self.data[4] = choicetext
        self.EndModal(retCode=1)
    
    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.data
        else:
            return 5101

    def isnum(self, string):
        try:
            if string=='NaN':
                return False
            float(string)
            return True
        except ValueError:
            return False

if __name__ == "__main__":
    import os
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            data = ['测试1', '测试2', '测试3', '测试4', '电缆']
            dia = DiaTable4Add(self, 'haha', data=data, name='haha')
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()